package database

import (
	"fmt"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"mon-go-web/internal/models"
	"mon-go-web/pkg/logger"
)

var DB *gorm.DB

func InitDB() {
	// 构建数据库连接字符串
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		viper.GetString("database.user"),
		viper.GetString("database.password"),
		viper.GetString("database.host"),
		viper.GetInt("database.port"),
		viper.GetString("database.name"),
	)

	// 连接数据库
	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		logger.Logger.Error("Failed to connect to database", zap.Error(err))
		panic("Failed to connect to database: " + err.Error())
	}
	logger.Logger.Info("Database connected successfully",
		zap.String("host", viper.GetString("database.host")),
		zap.String("database", viper.GetString("database.name")),
	)

	// 自动迁移表结构
	err = DB.AutoMigrate(&models.User{}, &models.Article{})
	if err != nil {
		logger.Logger.Error("Failed to auto-migrate tables", zap.Error(err))
		panic("Failed to auto-migrate tables: " + err.Error())
	}
	logger.Logger.Info("Tables migrated successfully",
		zap.Strings("tables", []string{"users", "articles"}),
	)
}
